<template>
    <div class="production-plan">
        <el-form-item>
            <el-button type="primary" @click="saveAll">保存</el-button>
        </el-form-item>
        <h3 class="title">生产派工</h3>
        <!-- 基本信息 -->
        <el-form :model="formData" :rules="rules" label-width="120px" ref="formRef" class="bordered-form">
            <el-row :gutter="24">
                <el-col :span="7">
                    <el-form-item label="单据主题" prop="documentSubject" class="bordered-form-item">
                        <el-input v-model="formData.documentSubject" required></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="单据编号" prop="documentNumber" class="bordered-form-item">
                        <el-input placeholder="保存后自动生成" readonly v-model="formData.documentNumber"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="来源单据类型" prop="sourceDocumentType" class="bordered-form-item">
                        <el-select
                            v-model="formData.sourceDocumentType"
                            placeholder="无来源"
                            clearable
                            required
                        >
                            <el-option label="销售合同" value="销售合同" />
                            <el-option label="生产订单" value="生产订单" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="来源单据" prop="sourceDocument" class="bordered-form-item">
                        <el-input v-model="formData.sourceDocument" required></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="制单人员" prop="documentMakers" class="bordered-form-item">
                        <el-input v-model="formData.documentMakers" readonly required></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="制单日期" prop="documentDate" class="bordered-form-item">
                        <el-date-picker
                            v-model="formData.documentDate"
                            type="date"
                            required
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="*关联项目" prop="associatedProjects" class="bordered-form-item">
                        <el-input
                            placeholder="请输入"
                            v-model="formData.associatedProjects"
                            required
                        >
                            <template #suffix>
                                <el-button size="mini" @click="openAssociatedItemDialog">
                                    <i class="el-icon-search"></i>
                                </el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="14">
                    <el-form-item label="概要" prop="outline" class="bordered-form-item">
                        <el-input v-model="formData.outline" type="textarea" rows="3" required></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 生产计划明细 -->
        <div class="detail-section">
            <h4 class="sub-title">生产派工明细</h4>
            <el-button size="small" @click="addNewRow">新增行</el-button>
            <!-- <el-button size="small" @click="batchSaveDetails">批量保存明细</el-button> -->
            <el-table :data="planDetailsList" border style="width: 100%">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="序号" width="80">
                    <template #default="{ row }">
                        <span>{{ row.dispatchDetailsId }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="派工主题" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.dispatchTheme"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="被派人员" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.assignedPersonnel"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="订单数量" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.orderQuantity"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="已派工数量" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.dispatchedSum"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="本次派工数量" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.dispatchedNumber"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="产品名称" width="180px">
                    <template #default="{ row }">
                        <el-input
                            v-model="row.productName"
                            :readonly="row.isSaved"
                        >
                            <template #suffix>
                                <el-button size="mini" @click="openProductNameDialog(row)">
                                    <i class="el-icon-search"></i>
                                </el-button>
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="产品编号" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.productNumber" :disabled="row.productInfoFilled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.specifications" :disabled="row.productInfoFilled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="单位" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.unit" :disabled="row.productInfoFilled"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="批号" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.dispatchProductNo"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="生产类型" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.produceType"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料清单" width="180px">
                    <template #default="{ row }">
                        <el-input
                            v-model="row.billMaterials"
                            :readonly="row.isSaved"
                        >
                            <template #suffix>
                                <el-button size="mini" @click="openBillMaterialsDialog(row)">
                                    <i class="el-icon-search"></i>
                                </el-button>
                            </template>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="计划开工日期" width="280px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.constructionPlannedDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="计划完工日期" width="280px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.scheduledCompletionDate"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="交货日期" width="280px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.delivery"
                            type="date"
                            @change="checkDateOrder(row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="备注" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.remark" type="textarea" rows="3"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="updateDetailTable(row)">保存本条</el-button>
                        <el-button size="small" type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 附件部分 -->
        <div class="attachment-section">
            <h4 class="sub-title">附件管理</h4>
            <el-form ref="formRef" :model="formData" label-width="100px">
                <el-form-item>
                    <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
                               :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
                        <el-button type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>

        <!-- 关联项目选择对话框 -->
        <el-dialog
            v-model="associatedItemDialogVisible"
            width="500"
            title="关联项目选择"
            append-to-body
        >
            <el-table
                :data="associatedItems"
                highlight-current-row
                border
                size="small"
                @current-change="handleAssociatedItemChange"
            >
                <el-table-column type="index" width="50" />
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="projectNum" label="项目编号" />
                <el-table-column prop="projectTime" label="日期" />
                <el-table-column prop="projectPeople" label="负责人" />
                <el-table-column prop="projectTypeId" label="项目分类" />
            </el-table>
            <template #footer>
                <el-button @click="pickAssociatedItem">确定</el-button>
            </template>
        </el-dialog>

        <!-- 产品名称选择对话框 -->
        <el-dialog
            v-model="productNameDialogVisible"
            width="500"
            title="产品名称选择"
            append-to-body
        >
            <el-table
                :data="productNames"
                highlight-current-row
                border
                size="small"
                @current-change="handleProductNameChange"
            >
                <el-table-column type="index" label="序号" />
                <el-table-column property="productsNumber" label="产品编号" />
                <el-table-column property="productsName" label="产品名称" />
                <el-table-column property="productsNum" label="规格型号" />
                <el-table-column property="productsUnit" label="单位" />
            </el-table>
            <template #footer>
                <el-button @click="pickProductName">确定</el-button>
            </template>
        </el-dialog>

        <!-- 物料清单选择对话框 -->
        <el-dialog
            v-model="billMaterialsDialogVisible"
            width="500"
            title="物料清单选择"
            append-to-body
        >
            <el-table
                :data="billMaterialsList"
                highlight-current-row
                border
                size="small"
                @current-change="handleBillMaterialsChange"
                height="300"
            >
                <el-table-column type="index" width="50" label="序号" />
                <el-table-column property="documentNo" label="清单编号" />
                <el-table-column property="bomSubject" label="清单主题" />
                <el-table-column property="productName" label="产品名称" />
                <el-table-column property="creator" label="添加人员" />
            </el-table>
            <template #footer>
                <el-button @click="pickBillMaterials">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { write, read } from '@/axios/axiosHelper';

const formRef = ref(null);
const currentUser = ref("admin");
const route = useRoute();

// 主表单数据
const formData = reactive({
    documentSubject: "",
    documentNumber: "",
    sourceDocumentType: "",
    sourceDocument: "",
    documentMakers: "admin",
    documentDate: "",
    associatedProjects: "",
    outline: "",
    documentsId: '1',
    dispatchProductId: route.query.dispatchProductId
});

// 主表单验证规则
const rules = reactive({
    documentSubject: [
        { required: true, message: '单据主题不能为空', trigger: 'blur' }
    ],
    associatedProjects: [
        { required: true, message: '关联项目不能为空', trigger: 'blur' }
    ],
    documentMakers: [
        { required: true, message: '制单人员不能为空', trigger: 'blur' }
    ],
    documentDate: [
        { required: true, message: '制单日期不能为空', trigger: 'blur' }
    ],
    outline: [
        { required: true, message: '概要不能为空', trigger: 'blur' }
    ]
});

// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 关联项目数据
const associatedItems = ref([]);

// 产品名称数据
const productNames = ref([]);

// 物料清单数据
const billMaterialsList = ref([]);

// 对话框显示状态
const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

const billMaterialsDialogVisible = ref(false);
const currentBillMaterialsRow = ref(null);
const currentBillMaterials = ref({});

// 获取关联项目数据
const fetchAssociatedProjects = () => {
    read.get('w-read/api/Project/ShowProject')
       .then(res => {
            associatedItems.value = res.data.data;
            console.log("关联项目数据：", associatedItems.value);
        })
       .catch(error => {
            console.error('获取关联项目数据失败:', error);
            ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
        });
};

// 获取产品信息
const fetchProducts = () => {
    read.get("w2-read/api/Products/GetProducts")
       .then(res => {
            productNames.value = res.data.data;
            console.log("产品数据：", productNames.value);
            nextTick(() => {
                // 强制更新表格
            });
        })
       .catch(error => {
            console.error('获取产品信息失败:', error);
            ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
        });
};

// 获取物料清单数据
const fetchBillMaterials = () => {
    read.get('l-read/api/GetValues/ZXSDMaterials')
       .then(res => {
            billMaterialsList.value = res.data.data;
            console.log("物料清单数据：", billMaterialsList.value);
            nextTick(() => {
                // 强制更新表格
            });
        })
       .catch(error => {
            console.error('获取物料清单数据失败:', error);
            ElMessage.error('获取物料清单数据失败，请检查网络或联系管理员');
        });
};

// 查询主表数据
const getbyidDispatchProduct = async () => {
    try {
        const response = await write.get('w-write/api/Report/GetBYIdDispatchProduct', {
            params: {
                dispatchProductId: route.query.dispatchProductId
            }
        });
        if (response.data.code === 100) {
            Object.assign(formData, response.data.data[0]);
        } else {
            ElMessage.error(`查询主表数据失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('查询主表数据发生错误:', error);
        ElMessage.error('查询主表数据发生错误，请检查网络或联系管理员');
    }
};

// 查询明细表数据
const getbyidDispatchProductDetail = async () => {
    try {
        const response = await read.get('w-read/api/Report/GetBYIdDispatchDetails', {
            params: {
                dispatchProductId: route.query.dispatchProductId
            }
        });
        if (response.data.code === 100) {
            planDetailsList.value = response.data.data;
        } else {
            ElMessage.error(`查询明细表数据失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('查询明细表数据发生错误:', error);
        ElMessage.error('查询明细表数据发生错误，请检查网络或联系管理员');
    }
};

onMounted(() => {
    console.log('dispatchProductId:', route.query.dispatchProductId); // 检查 dispatchProductId 是否正确获取
    fetchAssociatedProjects();
    fetchProducts();
    fetchBillMaterials();
    getbyidDispatchProduct();
    getbyidDispatchProductDetail();
});

// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
    associatedItemDialogVisible.value = true;
};

// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
    currentAssociatedItem.value = val;
};

// 选择关联项目
const pickAssociatedItem = () => {
    if (currentAssociatedItem.value) {
        formData.associatedProjects = currentAssociatedItem.value.projectName;
        associatedItemDialogVisible.value = false;
    }
};

// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
    if (productNames.value.length === 0) {
        ElMessage.warning('产品信息正在加载，请稍后重试');
        return;
    }
    currentProductNameRow.value = row;
    productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
    currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
    if (currentProductName.value && currentProductNameRow.value) {
        currentProductNameRow.value.productName = currentProductName.value.productsName;
        currentProductNameRow.value.productNumber = currentProductName.value.productsNumber;
        currentProductNameRow.value.specifications = currentProductName.value.productsNum;
        currentProductNameRow.value.unit = currentProductName.value.productsUnit;
        currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
        productNameDialogVisible.value = false;
    }
};

// 打开物料清单选择对话框
const openBillMaterialsDialog = (row) => {
    currentBillMaterialsRow.value = row;
    billMaterialsDialogVisible.value = true;
};

// 当前选中的物料清单行
const handleBillMaterialsChange = (val) => {
    currentBillMaterials.value = val;
};

// 选择物料清单
const pickBillMaterials = () => {
    if (currentBillMaterials.value && currentBillMaterialsRow.value) {
        currentBillMaterialsRow.value.billMaterials = currentBillMaterials.value.bomSubject;
        billMaterialsDialogVisible.value = false;
    }
};

// 新增行
const addNewRow = () => {
    planDetailsList.value.push({
        dispatchDetailsId: planDetailsList.value.length + 1,
        dispatchTheme: "",
        assignedPersonnel: "",
        orderQuantity: '',
        dispatchedSum: '',
        dispatchedNumber: '',
        productName: "",
        productNumber: "",
        specifications: "",
        unit: "",
        dispatchProductNo: "",
        produceType: "",
        billMaterials: "",
        constructionPlannedDate: null,
        scheduledCompletionDate: null,
        delivery: null,
        remark: "",
        dispatchProductId: formData.dispatchProductId, // 确保新增行包含正确的 dispatchProductId
        isSaved: false
    });
};

// 检查日期顺序
const checkDateOrder = (row) => {
    const startDate = new Date(row.constructionPlannedDate);
    const endDate = new Date(row.scheduledCompletionDate);
    const deliveryDate = new Date(row.delivery);

    if (startDate && endDate && startDate > endDate) {
        ElMessage.error('计划完工日期不能小于计划开工日期');
        row.scheduledCompletionDate = null;
    }

    if (endDate && deliveryDate && endDate > deliveryDate) {
        ElMessage.error('交货日期不能小于计划完工日期');
        row.delivery = null;
    }
};

// 修改主表数据
const updateMainTable = async () => {
    try {
        const response = await write.post('w-write/api/DispatchProduct/UpdateDispatchProduct', formData);
        if (response.data.code === 100) {
            ElMessage.success('主表数据修改成功');
        } else {
            ElMessage.error(`主表数据修改失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('修改主表数据发生错误:', error);
        ElMessage.error('修改主表数据发生错误，请检查网络或联系管理员');
    }
};

// 修改明细表数据
const updateDetailTable = async (row) => {
    try {
        const dataToSend = { 
            ...row,
            dispatchProductId: formData.dispatchProductId, // 确保传递正确的 dispatchProductId
            id: row.dispatchDetailsId 
        };
        console.log('提交的明细数据:', dataToSend); // 检查提交的数据
        const response = await write.post('w-write/api/DispatchProduct/UpdateDispatchDetails', dataToSend);
        if (response.data.code === 100) {
            row.isSaved = true;
            ElMessage.success('明细数据修改成功');
        } else {
            ElMessage.error(`明细 ${row.dispatchTheme} 修改失败：${response.data.message}`);
        }
    } catch (error) {
        console.error(`修改明细 ${row.dispatchTheme} 发生错误:`, error);
        ElMessage.error(`修改明细 ${row.dispatchTheme} 发生错误，请检查网络或联系管理员`);
    }
};

// 修改主表单和明细
const saveAll = async () => {
    if (formRef.value) {
        const isValid = await formRef.value.validate();
        if (isValid) {
            await updateMainTable();
            const updatePromises = planDetailsList.value.map(row => updateDetailTable(row));
            await Promise.all(updatePromises);
        }
    }
};

// 删除单条明细
const deleteDetail = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = planDetailsList.value.indexOf(row);
        if (index !== -1) {
            planDetailsList.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

const headers = {}; // 这里假设 headers 为空，你可以根据实际情况修改
const customRequest = async (options) => {
    const formData = new FormData();
    formData.append('file', options.file);
    const response = await axios.post(options.action, formData, {
        headers: headers
    });
    options.onSuccess(response.data);
    if (response.data != null) {
        alert("添加成功");
        return;
    } else {
        alert("添加失败");
        return;
    }
};

const handleError = (error) => {
    ElMessage.error('上传失败: ' + (error.response?.data?.error || error.message));
};

const uploadRef = ref(null);
const submitForm = () => {
    uploadRef.value.submit();
};
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section {
    width: 100%;
}
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}

.el-input[readonly],
.el-date-editor[readonly],
.el-input-number[disabled] {
    background-color: #f5f7fa;
    cursor: not-allowed;
}

.bordered-form {
    border: 1px solid #ccc; /* 设置边框线，颜色为灰色，宽度为 1px */
    padding: 20px; /* 为表单内部添加一些内边距，使内容与边框有一定距离 */
    border-radius: 4px; /* 为边框添加圆角 */
}

.bordered-form-item {
    border: 1px solid #e4e7ed; /* 表单项边框颜色 */
    border-radius: 4px;
    padding: 10px;
    margin-bottom: 15px; /* 表单项之间的间距 */
}
</style>    